package com.ky.serialport.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.ky.serialport.message.MessageEvent;
import com.ky.myserialport.R;
import com.ky.serialport.sensor.Dt805DataBean;
import com.ky.serialport.sensor.DtConnectBean;
import com.ky.serialport.sensor.Dt405_410DataBean;
import com.ky.serialport.sensor.DtDisConnectBean;
import com.ky.serialport.sensor.UldConnectedBean;
import com.ky.serialport.sensor.UldDataBean;
import com.ky.serialport.sensor.UldDisconnectBean;
import com.ky.serialport.utils.FormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class BlueToothDtUldService extends Service {

    private NotificationManager notificationManager;
    private BlueToothManager blueToothManager;
    private BluetoothAdapter mBluetooth;

    private Dt405_410DataBean dt405_410DataBean = new Dt405_410DataBean();
    private Dt805DataBean dt805DataBean = new Dt805DataBean();
    private DtConnectBean dtConnect = new DtConnectBean();
    private DtDisConnectBean dtDisconnect = new DtDisConnectBean();

    private UldDataBean uldData = new UldDataBean();
    private UldConnectedBean uldConnect = new UldConnectedBean();
    private UldDisconnectBean uldDisconnectBean = new UldDisconnectBean();


    @Override
    public void onCreate() {
        super.onCreate();
        FormatUtils.init();
        EventBus.getDefault().register(this);

        //获取Bluetooth适配器
        mBluetooth = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetooth.isEnabled()) {
            mBluetooth.enable();
        }
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void getEvent(MessageEvent event) {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 注册通知服务
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        builder.setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.mipmap.lanya)) // 设置下拉列表中的图标(大图标)
                .setContentTitle("蓝牙数据") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.lanya) // 设置状态栏内的小图标
                .setContentText("数据收取中...") // 设置上下文内容
                .setWhen(System.currentTimeMillis())// 设置该通知发生的时间
                .setVibrate(null)
                .setVibrate(new long[]{0l})
                .setSound(null)
                .setLights(0,0,0)
                .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);

        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.FLAG_ONLY_ALERT_ONCE; /*设置为默认的声音*/
        startForeground(111, notification);
        bluetoothControl();
        return super.onStartCommand(intent, flags, startId);
    }


    /**
     * 发送两种状态：连接蓝牙、失去蓝牙（蓝牙数据传输包间隔太小，按普通刷新方式有可能会导致传感器自定义控件绘制过于频繁，长时间后造成卡顿）
     * 计算蓝牙风速的温度、风速，
     * 并且发送通知给
     */
    private void bluetoothControl() {
        blueToothManager = new BlueToothManager(this, true);
        blueToothManager.initBlueTooth(getApplication());
        blueToothManager.setOnGetDataListener(new BlueToothManager.OnGetDataListener() {
            @Override
            public void status(String type , byte[] dataByte, int assi) {
                if (type.startsWith("T405i") || type.startsWith("T410i")){
                    if (dataByte != null && dataByte.length == 8) {//风速
                        dt405_410DataBean.caculateFengSu(dataByte);
                    }
                    if (dataByte != null && dataByte.length == 11) {//温度
                        dt405_410DataBean.caculateWenDu(dataByte);
                    }
                    EventBus.getDefault().post(dt405_410DataBean);
                }else if(type.startsWith("T805i")){
                    EventBus.getDefault().post(dt805DataBean.setName("T805i").setData(dataByte));
                }else if(type.startsWith("UT383BT")){
                    EventBus.getDefault().post(uldData.setData(dataByte).setName("UT383BT"));
                }
            }
        });

        blueToothManager.setOnConnectedListener(new BlueToothManager.OnConnectedListener() {
            @Override
            public void connected(String type , Long time) {
                if (type.startsWith("T405i")){
                    EventBus.getDefault().post(dtConnect.setName("T405i"));
                }else if(type.startsWith("T410i")){
                    EventBus.getDefault().post(dtConnect.setName("T410i"));
                }else if(type.startsWith("T805i")){
                    EventBus.getDefault().post(dtConnect.setName("T805i"));
                }else if(type.startsWith("UT383BT")){
                    EventBus.getDefault().post(uldConnect.setName("UT383BT"));
                }
            }
        });

        blueToothManager.setOnDisConnectedListener(new BlueToothManager.OnDisConnectedListener() {
            @Override
            public void disConnected(String type ,Long time) {
                if (type.startsWith("T405i")){
                    EventBus.getDefault().post(dtDisconnect.setName("T405i"));
                }else if(type.startsWith("T410i")){
                    EventBus.getDefault().post(dtDisconnect.setName("T410i"));
                }else if(type.startsWith("T805i")){
                    EventBus.getDefault().post(dtDisconnect.setName("T805i"));
                }else if(type.startsWith("UT383BT")){
                    EventBus.getDefault().post(uldDisconnectBean.setName("UT383BT"));
                }
            }
        });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知
        notificationManager.cancel(111);
        blueToothManager.destroy();

//        if (mBluetooth!=null && mBluetooth.isEnabled()) {
//            mBluetooth.disable();
//            mBluetooth = null;
//        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
